package com.edou.cms.controller.admin;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.edou.base.controller.BaseController;
import com.edou.cms.dto.CmsAdvCondition;
import com.edou.cms.entity.CmsAdv;
import com.edou.cms.form.CmsAdvForm;
import com.edou.cms.service.ICmsAdvService;

/**
 * 
 * 广告管理
 * @author 方泉
 *
 */
@Controller("advAdminController")
@Scope("prototype")
@RequestMapping(value = "/admin/cms/adv")
public class AdvAdminController extends BaseController {
	
	private Log logger = LogFactory.getLog(AdvAdminController.class);

	@Resource
	private ICmsAdvService cmsAdvService;
	
	
	@RequestMapping(value = "/index.htm", method = RequestMethod.GET)
	public ModelAndView index(CmsAdvForm model) {
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/cms/adv_list");
		return view;
	}
	
	@RequestMapping(value = "/to_add.htm", method = RequestMethod.GET)
	public ModelAndView toAdd(CmsAdvForm model) {
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/cms/add");
		return view;
	}
	
	@RequestMapping(value = "/to_manage.htm", method = RequestMethod.GET)
	public ModelAndView toManage(CmsAdvForm model) {
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/cms/adv_manage");
		Map<String,Object> data = view.getModel();
		data.put("item", model.getItem());
		
		if(StringUtils.isNotBlank(model.getItem().getId())){
			// 获得部门信息
			CmsAdv item = cmsAdvService.getAdvById(model.getItem().getId());
			data.put("item", item);
		}
		return view;
	}
	
	/**
	 * 分页查询文章
	 */
	@RequestMapping(value = "/list_adv.htm", method = RequestMethod.POST)
	public void searchUserList(@ModelAttribute CmsAdvForm cmsAdvForm,HttpServletRequest request,HttpServletResponse response) {
		try{
			CmsAdvCondition condition = cmsAdvForm.getCondition();
			cmsAdvService.listAdvByPage(cmsAdvForm.getPageResult(),condition);
			JSONObject root = toPageJson(cmsAdvForm.getPageResult(), new String []{"id","name","note","photoWidth","photoHeight","maxPhotoNum"});
			ajaxPageResult(root,response);
		}catch(Exception ex){
			String msg = "查询文章时发生异常："+ex.getMessage();
			logger.error(msg,ex);
			ajaxJSON(Status.error, "查询失败");
		}
	}
	
}
